<?php

namespace app\common\behavior;


use app\common\library\Wechat;
use app\common\model\NotificationLog;
use app\common\model\User;
use app\common\model\UserOauth;
use think\Log;

class Notification
{
    protected $group_id = 1; // 超级管理员 group_id
    protected $templateIds = [
        'created'       => 'ZiQpXe9BVAMTt2Elr1MknS0CD0QMNxMWEuGaLfWhRjs',
        'picked'        => 'lCFhuuEN9KAf9eoFcZngxPalduMKhdpqB_RRy9S5ruk',
        'serviced'      => 'imyc6U24sklt2ZTSXrt9dXQzt-bAjE9qOJDQqR0D9bY',
        'approves'      => 'uDNK3HpYaEEQAnmm0ylcJ8wPH0oDSKFZ2NWlEL1X0pw',
        'work_urge'     => 'OAMsj9r97NUj0tgexg0GsWUPZ6xFxYpL23If0NpZses',   //工单催促
        'work_success'  => 'iOWRwvO8W_XY38U7uxc_VO7ZqWyytbQJzIczODNfl3o',   //工单完成

    ];
    //发任务通知
    public function sendMessage($params){
        $task = $params['task'];
        if (!$task){
            return false;
        }
        $action = $params['action'];
        $result = [];
        $wechat = new Wechat('wxOfficialAccount');
        switch ($action) {
            case 'created': //新工单通知
                $user = User::where('id',$task->user_id)->find();
                if(!$user){
                    NotificationLog::add_log('task',$task->id,0,'派单人不存在');
                    return false;
                }
                $openid = $this->getUserOpenid($task->pick_uid);
                if (!$openid){
                    NotificationLog::add_log('task',$task->id,0,'openid不存在');
                    return false;
                }
                $time = $task->edittime > 0 ? $task->edittime : $task->createtime;
                $messageData = [
                    "openId"        => $openid,
                    "templateId"    => $this->templateIds['created'],
                    "formId"        => "task_".$task->id,
                    "miniprogram"   => [
                        "appid"     => get_addon_config('dep')['wxMiniProgram']['app_id'],
                        "pagepath"  => "/pages/index/detail?id=".$task->id."&type=".$task->status,
                    ],
                    "data"          => [
                        "character_string10"     => ["value"=>$task->order_sn,],
                        "thing13"                => ["value"=>$user->nickname,],
                        "time4"                  => ["value"=>date("Y-m-d H:i:s",$time),],
                        "thing11"                => ["value"=>$task->car_number,],
                    ]
                ];
                $result[] = $wechat->sendTemplateMessage($messageData);
                break;
            case 'picked': //已取件通知
                //通知超级管理员
                $admin_openids = $this->getAdminOpenids();
                if (!$admin_openids){
                    NotificationLog::add_log('task',$task->id,0,'超级管理员openid不存在');
                    return false;
                }
                foreach ($admin_openids as $openid){
                    $messageData = [
                        "openId"        => $openid,
                        "templateId"    => $this->templateIds['picked'],
                        "formId"        => "task_".$task->id,
                        "miniprogram"   => [
                            "appid"     => get_addon_config('dep')['wxMiniProgram']['app_id'],
                            "pagepath"  => "/pages/index/detail?id=".$task->id."&type=".$task->status,
                        ],
                        "data"          => [
                            "character_string6"     => ["value"=>$task->order_sn,],
                            "time5"                 => ["value"=>$task->ext_arr['pick_time_text'],],
                            "thing12"               => ["value"=>$task->name_4s,], //取件地址
                        ]
                    ];
                    $result[] = $wechat->sendTemplateMessage($messageData);
                }
                break;
            case 'serviced': //维修完成后
                $openid = $this->getUserOpenid($task->pick_uid);
                if (!$openid){
                    NotificationLog::add_log('task',$task->id,0,'openid不存在');
                    return false;
                }
                $time = $task->edittime > 0 ? $task->edittime : $task->createtime;
                $messageData = [
                    "openId"        => $openid,
                    "templateId"    => $this->templateIds['serviced'],
                    "formId"        => "task_".$task->id,
                    "miniprogram"   => [
                        "appid"     => get_addon_config('dep')['wxMiniProgram']['app_id'],
                        "pagepath"  => "/pages/index/detail?id=".$task->id."&type=".$task->status,
                    ],
                    "data"          => [
                        "character_string5"     => ["value"=>$task->order_sn,],
                        "time14"                => ["value"=>date("Y-m-d",$time),],
                        "time3"                 => ["value"=>$task->ext_arr['serviced_time_text'],],
                    ]
                ];
                $result[] = $wechat->sendTemplateMessage($messageData);
                break;
        }
        //消息发失败添加log
        foreach ($result as $res){
            if ($res['errcode'] != 0) {
                NotificationLog::add_log('task',$task->id,$res['errcode'],$res['errmsg']);
                return false;
            }
        }
        /*
         * 消息发失败
         *array(2) {
              ["errcode"] => "40037"
              ["errmsg"] => "invalid template_id rid: 6747cb49-1f64921c-2e25353a"
            }
         *
         *
         * 消息发成功
         * array(3) {
              ["errcode"] => int(0)
              ["errmsg"] => string(2) "ok"
              ["msgid"] => int(3786960237035700224)
            }
         */
    }


    //发审批通知
    public function sendSpMessage($params)
    {
        $approves = $params['approve'];
        if (!$approves){
            return false;
        }
        $action = $params['action'];
        $result = [];
        $wechat = new Wechat('wxOfficialAccount');
        switch ($action) {
            case 'wait': //待审批
                $user = User::where('id',$approves->user_id)->find();
                if(!$user){
                    NotificationLog::add_log('approves',$approves->id,0,'提交审批的用户不存在了');
                    return false;
                }
                $openid = $this->getUserOpenid($approves->wait_uid);
                if (!$openid){
                    NotificationLog::add_log('approves',$approves->id,0,'待审批人openid不存在');
                    return false;
                }
                $thing7 = $approves->type_text.' - 待审批';
                $messageData = [
                    "openId"        => $openid,
                    "templateId"    => $this->templateIds['approves'],
                    "formId"        => "approves_".$approves->id,
                    "miniprogram"   => [
                        "appid"     => get_addon_config('dep')['wxMiniProgram']['app_id'],
                        "pagepath"  => "pages/Work/index",
                    ],
                    "data"          => [
                        "character_string6"     => ["value"=>$approves->id,],
                        "thing7"                => ["value"=>$thing7,],
                        "thing8"                => ["value"=>$user->nickname,],
                        "time9"                 => ["value"=>date("Y-m-d H:i:s",time()),],
                    ]
                ];
                $result[] = $wechat->sendTemplateMessage($messageData);
                break;
            case 'success': //审批完成
                $user = User::where('id',$approves->user_id)->find();
                if(!$user){
                    NotificationLog::add_log('approves',$approves->id,0,'提交审批的用户不存在了');
                    return false;
                }
                $openid = $this->getUserOpenid($approves->user_id);
                if (!$openid){
                    NotificationLog::add_log('approves',$approves->id,0,'openid不存在');
                    return false;
                }
                $thing7 = $approves->type_text.' - 审批通过';
                $messageData = [
                    "openId"        => $openid,
                    "templateId"    => $this->templateIds['approves'],
                    "formId"        => "approves_".$approves->id,
                    "miniprogram"   => [
                        "appid"     => get_addon_config('dep')['wxMiniProgram']['app_id'],
                        "pagepath"  => "pages/Work/index",
                    ],
                    "data"          => [
                        "character_string6"     => ["value"=>$approves->id,],
                        "thing7"                => ["value"=>$thing7,],
                        "thing8"                => ["value"=>$user->nickname,],
                        "time9"                 => ["value"=>date("Y-m-d H:i:s",time()),],
                    ]
                ];
                $result[] = $wechat->sendTemplateMessage($messageData);
                break;
            case 'refuse': //审批完成
                $user = User::where('id',$approves->user_id)->find();
                if(!$user){
                    NotificationLog::add_log('approves',$approves->id,0,'提交审批的用户不存在了');
                    return false;
                }
                $openid = $this->getUserOpenid($approves->user_id);
                if (!$openid){
                    NotificationLog::add_log('approves',$approves->id,0,'openid不存在');
                    return false;
                }
                $thing7 = $approves->type_text.' - 审批不通过';
                $messageData = [
                    "openId"        => $openid,
                    "templateId"    => $this->templateIds['approves'],
                    "formId"        => "approves_".$approves->id,
                    "miniprogram"   => [
                        "appid"     => get_addon_config('dep')['wxMiniProgram']['app_id'],
                        "pagepath"  => "pages/Work/index",
                    ],
                    "data"          => [
                        "character_string6"     => ["value"=>$approves->id,],
                        "thing7"                => ["value"=>$thing7,],
                        "thing8"                => ["value"=>$user->nickname,],
                        "time9"                 => ["value"=>date("Y-m-d H:i:s",time()),],
                    ]
                ];
                $result[] = $wechat->sendTemplateMessage($messageData);
                break;
        }

        //消息发失败添加log
        foreach ($result as $res){
            if ($res['errcode'] != 0) {
                NotificationLog::add_log('approves',$approves->id,$res['errcode'],$res['errmsg']);
                return false;
            }
        }
    }

    //发仪事通知
    public function sendWorkMessage($params)
    {
        $backlog = $params['backlog'];
        if (!$backlog){
            return false;
        }
        $action = $params['action'];
        $result = [];
        $wechat = new Wechat('wxOfficialAccount');
        switch ($action) {
            case 'created': //创建完成
                $openid = $this->getUserOpenid($backlog->work_uid);
                if (!$openid){
                    NotificationLog::add_log('backlog',$backlog->id,0,'仪事执行者openid不存在');
                    return false;
                }
                $messageData = [
                    "openId"        => $openid,
                    "templateId"    => $this->templateIds['work_urge'],
                    "formId"        => "backlogs_".$backlog->id,
                    "miniprogram"   => [
                        "appid"     => get_addon_config('dep')['wxMiniProgram']['app_id'],
                        "pagepath"  => "pages/Work/index",
                    ],
                    "data"          => [
                        "character_string1"     => ["value"=>$backlog->work_sn,],
                        "thing15"               => ["value"=>$backlog->work_nickname,],
                        "time16"                => ["value"=>date("Y-m-d H:i:s",$backlog->createtime),],
                        "thing11"               => ["value"=>$backlog->title,],
                    ]
                ];
                $result[] = $wechat->sendTemplateMessage($messageData);
                break;
            case 'success': //仪事完成
                $openid = $this->getUserOpenid($backlog->user_id);
                if (!$openid){
                    NotificationLog::add_log('backlog',$backlog->id,0,'仪事发起者openid不存在');
                    return false;
                }
                $messageData = [
                    "openId"        => $openid,
                    "templateId"    => $this->templateIds['work_success'],
                    "formId"        => "backlogs_".$backlog->id,
                    "miniprogram"   => [
                        "appid"     => get_addon_config('dep')['wxMiniProgram']['app_id'],
                        "pagepath"  => "pages/Work/index",
                    ],
                    "data"          => [
                        "character_string2"     => ["value"=>$backlog->work_sn,],
                        "thing3"                => ["value"=>$backlog->title,],
                        "time11"                => ["value"=>date("Y-m-d H:i:s",$backlog->finishtime),],
                        "thing10"               => ["value"=>$backlog->work_nickname,],
                    ]
                ];
                $result[] = $wechat->sendTemplateMessage($messageData);
                break;
        }

        //消息发失败添加log
        foreach ($result as $res){
            if ($res['errcode'] != 0) {
                NotificationLog::add_log('backlog',$backlog->id,$res['errcode'],$res['errmsg']);
                return false;
            }
        }
    }


    //获取用户Openid
    public function getUserOpenid($user_id)
    {
        $user = User::where('id',$user_id)->find();
        if (!$user){
            return false;
        }
        $oauth = UserOauth::where('user_id',$user->id)->find();
        if (!$oauth){
            return false;
        }
        return $oauth->openid;
    }

    //获取超级管理员的openid数组
    public function getAdminOpenids()
    {
        $user_ids = User::where('FIND_IN_SET('.$this->group_id.',group_ids)')->column('id');
        if (!$user_ids){
            return [];
        }
        $openids = UserOauth::whereIn('user_id',$user_ids)->column('openid');
        return $openids;
    }

    /*
     * 订阅模板
     * {
        "template_list": [
            {
                "template_id": "rZM3BHeGhnfSZXVgxVIdyUP6iIYUgg9dTC2fPI9RfSQ",
                "title": "订阅模板消息",
                "primary_industry": "",
                "deputy_industry": "",
                "content": "{{content.DATA}}",
                "example": ""
            },
            {
                "template_id": "ZiQpXe9BVAMTt2Elr1MknS1UZi0hq7zKIrUV3cidPC8",
                "title": "新工单通知",
                "content": "报案号:{{character_string7.DATA}}\n派单人:{{thing13.DATA}}\n派单时间:{{time14.DATA}}\n发起时间:{{time4.DATA}}\n",
                "example": "报案号:RLDO2022210200N0009274\n派单人:张小二\n派单时间:2023-05-06\n发起时间:2022-12-28 17:00\n"
            },
            {
                "template_id": "geiWk3pXqHu27zRmBXTdASm5SN8cNTw5xhkCE_AeEoc",
                "title": "工单已接单通知",
                "content": "工单编号:{{character_string2.DATA}}\n接单时间:{{time3.DATA}}\n工单地址:{{thing5.DATA}}\n",
                "example": "工单编号:GD-20240202000001\n接单时间:2022-22-22 12:22:33\n工单地址:北京市朝阳区望京SOHO楼1703室\n"
            },
            {
                "template_id": "lCFhuuEN9KAf9eoFcZngxPalduMKhdpqB_RRy9S5ruk",
                "title": "取件通知",
                "content": "订单编号:{{character_string6.DATA}}\n取件时间:{{time5.DATA}}\n取件地点:{{thing12.DATA}}\n",
                "example": "订单编号:202312040001\n取件时间:2023/2/1 12:01\n取件地点:请到【思源堂】1楼充卡室领取\n"
            },
            {
                "template_id": "5-v8tG5_YsENAwA3lW8_-ezSpyzr8IzKtXEUfj3tPik",
                "title": "订单送达通知",
                "content": "到货时间:{{time2.DATA}}\n配送人员:{{thing5.DATA}}\n",
                "example": "到货时间:2023年08月31号\n配送人员:张山\n"
            },
            {
                "template_id": "ce_FRslHbOlPstuQZR5r3y_1XCG8xDS1ndjl8dIIxVw",
                "title": "新维修工单通知",
                "content": "工单编号:{{character_string2.DATA}}\n报修物品:{{thing19.DATA}}\n工程师:{{thing10.DATA}}\n",
                "example": "工单编号:20230107003002002\n报修物品:水龙头\n工程师:陈工程师\n"
            },
            {
                "template_id": "lCFhuuEN9KAf9eoFcZngxNesetzmj8qDAuX8VwOlC1o",
                "title": "取件通知",
                "content": "订单编号:{{character_string6.DATA}}\n取件地点:{{thing12.DATA}}\n",
                "example": "订单编号:202312040001\n取件地点:请到【思源堂】1楼充卡室领取\n"
            },
            {
                "template_id": "imyc6U24sklt2ZTSXrt9dXQzt-bAjE9qOJDQqR0D9bY",
                "title": "订单已完成通知",
                "content": "订单编号:{{character_string5.DATA}}\n下单时间:{{time14.DATA}}\n完成时间:{{time3.DATA}}\n",
                "example": "订单编号:110086\n下单时间:2022-10-22 13:20\n完成时间:05月27日17:50\n"
            },
            {
                "template_id": "uDNK3HpYaEEQAnmm0ylcJ8wPH0oDSKFZ2NWlEL1X0pw",
                "title": "单据待审批通知",
                "content": "单号:{{character_string6.DATA}}\n单据类型:{{thing7.DATA}}\n操作人:{{thing8.DATA}}\n操作时间:{{time9.DATA}}\n",
                "example": "单号:TS-ASD-0301-00012\n单据类型:备货耗材审批\n操作人:张三\n操作时间:2023-03-01 10:32:11\n"
            }
            ]
        }
     *
     *
     */
}
